// ignore_for_file: non_constant_identifier_names, duplicate_ignore, slash_for_doc_comments, use_build_context_synchronously, avoid_function_literals_in_foreach_calls, must_be_immutable, camel_case_types

import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:simple_animations/simple_animations.dart';
import 'package:slk/res/language/language.dart';

import 'common.dart';

/**
 * 动画淡入 封装
 */
enum AniProps { opacity, translateY }

class FadeAnimation extends StatelessWidget {
  final double delay;
  final Widget child;

  const FadeAnimation(this.delay, this.child, {super.key});

  @override
  Widget build(BuildContext context) {
    final tween = MovieTween()
      ..tween(
        AniProps.opacity,
        Tween(begin: 0.0, end: 1.0),
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeIn,
      )
      ..tween(
        AniProps.translateY,
        Tween(begin: -30.0, end: 0.0),
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );

    return PlayAnimationBuilder(
      delay: Duration(milliseconds: (500 * delay).round()),
      duration: tween.duration,
      tween: tween,
      child: child,
      builder: (context, child2, animation) => Opacity(
        opacity: child2.get(AniProps.opacity),
        child: Transform.translate(
            offset: Offset(0, child2.get(AniProps.translateY)), child: child),
      ),
    );
  }
}

// ignore: non_constant_identifier_names
void dq_MsgBox(BuildContext context, String title, String text,
    List<String> btnm, void Function(String)? cb, String enImage) async {
  await showDialog(
    barrierDismissible: false,
    context: context,
    builder: (context) => StatefulBuilder(
      builder: (context, setState) {
        Size screen = MediaQuery.of(context).size;
        return Material(
            type: MaterialType.transparency,
            child: Center(
              child: FadeAnimation(
                0.01,
                Container(
                  width: screen.width * 0.75,
                  height: screen.height * 0.75,
                  padding: EdgeInsets.all(screen.width * 0.05),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(20)),
                  child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(title, style: const TextStyle(fontSize: 20)),
                        SizedBox(height: screen.height * 0.02),
                        Expanded(
                          child: ListView(
                            children: [
                              Text(
                                text,
                                style: const TextStyle(
                                  fontWeight: FontWeight.bold, // 加粗
                                ),
                              ),
                              if (enImage == 'usingLocation' ||
                                  enImage == 'usingBle')
                                Image.asset('image/地图权限.jpg',
                                    width: screen.width * 0.3,
                                    height: screen.height * 0.3)
                            ],
                          ),
                        ),
                        SizedBox(height: screen.height * 0.02),
                        Row(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: btnm.map((e) {
                              return TextButton(
                                style: TextButton.styleFrom(
                                  textStyle:
                                      Theme.of(context).textTheme.labelLarge,
                                ),
                                child: Text(e),
                                onPressed: () {
                                  HapticFeedback.vibrate();
                                  Navigator.of(context).pop();

                                  if (cb != null) {
                                    cb(e);
                                  }
                                },
                              );
                            }).toList())
                      ]),
                ),
              ),
            ));
      },
    ),
  );
}

//创建一个提示框,无需按键
void dq_showTips(BuildContext context, String txt) {
  Timer(const Duration(milliseconds: 500), () {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return FadeAnimation(
          0.01,
          AlertDialog(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(20.0),
            ),
            title: Text(getUItext()['tips']),
            content: Text(txt),
            actions: [
              TextButton(
                onPressed: () {
                  HapticFeedback.vibrate();

                  Navigator.of(context).pop(); // 关闭对话框
                },
                child: Text(getUItext()['close']),
              ),
            ],
          ),
        );
      },
    );
  });
}

//创建带有一个按钮的自定义框,回调表示已点击,可自定义按键\窗体文本内容
void dq_showTipsBtn(
    BuildContext context, String text, String btntext, void Function()? cb) {
  Timer(const Duration(milliseconds: 500), () {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return FadeAnimation(
          0.01,
          AlertDialog(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(20.0),
            ),
            title: Text(getUItext()['tips']),
            content: Text(text),
            actions: [
              TextButton(
                onPressed: () {
                  HapticFeedback.vibrate();

                  Navigator.of(context).pop(); // 关闭对话框
                  if (cb != null) {
                    cb!();
                    cb = null;
                  }
                },
                child: Text(btntext),
              ),
            ],
          ),
        );
      },
    );
  });
}

// ignore: camel_case_types, must_be_immutable
class _showLoading extends Dialog {
  String text = '';
  _showLoading(this.text);

  @override
  Widget build(BuildContext context) {
    Size screen = MediaQuery.of(context).size;
    return Material(
      type: MaterialType.transparency,
      child: Center(
        child: ClipRRect(
          borderRadius: BorderRadius.circular(10),
          child: Container(
            height: screen.width / 3 + 10,
            width: screen.width / 3,
            color: Colors.grey,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                const SizedBox(
                  height: 50,
                  width: 50,
                  child: CircularProgressIndicator(
                    strokeWidth: 5,
                  ),
                ),
                // const Divider(height: 10),
                Center(
                  child: Text(
                    text,
                    style: const TextStyle(fontSize: 20),
                    textAlign: TextAlign.center,
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}

//创建 等待框,需手动关闭  Navigator.pop(context)
// ignore: non_constant_identifier_names
showLoading dq_showLoading(BuildContext cont, String text) {
  showLoading ld = showLoading();
  ld.show(cont, text);

  return ld;
}

class showLoading extends Dialog {
  BuildContext? _dialogContext;

  showLoading({super.key});

  /// 显示等待框
  void show(BuildContext cont, String text) {
    showDialog(
      barrierDismissible: false,
      context: cont,
      builder: (context) {
        _dialogContext = context;
        Size screen = MediaQuery.of(context).size;
        return Material(
          type: MaterialType.transparency,
          child: Center(
            child: ClipRRect(
              borderRadius: BorderRadius.circular(10),
              child: Container(
                height: screen.width / 3 + 10,
                width: screen.width / 3,
                color: Colors.grey,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    const SizedBox(
                      height: 50,
                      width: 50,
                      child: CircularProgressIndicator(
                        strokeWidth: 3,
                        // color: Colors.purple,
                      ),
                    ),
                    Center(
                      child: Text(text,
                          style: const TextStyle(fontSize: 20),
                          textAlign: TextAlign.center),
                    )
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  /// 关闭等待框
  void close() {
    if (_dialogContext != null) {
      LOGI('关闭等待框..');
      Navigator.of(_dialogContext!).pop();
    }
  }
}

/**
 * 创建消息询问框,有确认和取消,回调返回 true & false
 * ignore: non_constant_identifier_names
 * */
Future dq_showmsg(BuildContext context, String title, String content,
    void Function(bool)? cb) {
  return showDialog(
    context: context,
    builder: (context) {
      return FadeAnimation(
        0.01,
        AlertDialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20.0),
          ),
          title: Text(title),
          content: Text(content),
          actions: [
            TextButton(
              onPressed: () {
                HapticFeedback.vibrate();
                Navigator.of(context).pop(); // 关闭对话框

                if (cb != null) {
                  cb!(false);
                  cb = null;
                }
              },
              child: Text(getUItext()['Cancel']),
            ),
            TextButton(
              onPressed: () {
                HapticFeedback.vibrate();
                Navigator.of(context).pop(); // 关闭对话框

                if (cb != null) {
                  cb!(true);
                  cb = null;
                }
              },
              child: Text(getUItext()['Confirmed']),
            ),
          ],
        ),
      );
    },
  );
}

/// 创建底部弹出选项框,回调返回 index
// ignore: non_constant_identifier_names
Future dq_showModalBottomSheet(
    BuildContext context, List<String> item, void Function(int)? cb) {
  return showModalBottomSheet(
    context: context,
    builder: (BuildContext context0) {
      return SizedBox(
        height: item.length * 60,
        child: ListView.builder(
          itemCount: item.length,
          itemBuilder: (context1, index) {
            return ListTile(
              title: Text(
                item[index],
                textAlign: TextAlign.center,
                style: const TextStyle(fontSize: 20),
              ),
              onTap: () {
                Navigator.pop(context); // 关闭底部弹出窗口

                if (cb != null) {
                  cb!(index);
                  cb = null;
                }
              },
            );
          },
        ),
      );
    },
  );
}

/**
 * 模式锁定后面注释
 * // 'btnName':'xx',
/ / 'btnInfo':'xxx'
 */
Future dq_showModalBottomSheetEx(
    BuildContext context, List<Map> item, void Function(int)? cb) {
  return showModalBottomSheet(
    context: context,
    builder: (BuildContext context0) {
      return SizedBox(
        height: item.length * 60,
        child: ListView.builder(
          itemCount: item.length,
          itemBuilder: (context1, index) {
            return ListTile(
              title: Column(
                children: [
                  Text(
                    item[index]['btnName'],
                    textAlign: TextAlign.center,
                    style: const TextStyle(fontSize: 20),
                  ),
                  Text(
                    item[index]['btnInfo'],
                    textAlign: TextAlign.center,
                    style: const TextStyle(fontSize: 13, color: Colors.red),
                  )
                ],
              ),
              onTap: () {
                Navigator.pop(context); // 关闭底部弹出窗口

                if (cb != null) {
                  cb!(index);
                  cb = null;
                }
              },
            );
          },
        ),
      );
    },
  );
}

/// 弹框,带有输入框的 回调返回数据格式如下 {'type': false, 'data': _string}
dq_showInputDialog(BuildContext context, String title, String hintText,
    void Function(Map)? cb) {
  String string = ' ';
  TextEditingController controller = TextEditingController();
  return showDialog(
    context: context,
    builder: (BuildContext context) {
      return FadeAnimation(
        0.01,
        AlertDialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20.0),
          ),
          title: Text(title),
          content: TextField(
            controller: controller,
            decoration: InputDecoration(
              hintText: hintText,
            ),
            onChanged: (value) {
              string = value;
            },
          ),
          actions: [
            TextButton(
              child: Text(getUItext()['Cancel']),
              onPressed: () {
                HapticFeedback.vibrate();

                Navigator.of(context).pop();
                if (cb != null) {
                  cb!({'type': false, 'data': string});
                  cb = null;
                }
              },
            ),
            TextButton(
              child: Text(getUItext()['Confirmed']),
              onPressed: () {
                HapticFeedback.vibrate();

                Navigator.of(context).pop();
                if (cb != null) {
                  cb!({'type': true, 'data': string});
                  cb = null;
                }
              },
            ),
          ],
        ),
      );
    },
  ).then((value) {
    controller.dispose();
  });
}

/**
 * 获取权限
 */
Future dq_getPermission(BuildContext context, List<Permission> permissions,
    void Function(bool)? cb) async {
  String tipsContext = '';
  PermissionStatus res;
  String? enImage;

  switch (permissions[0]) {
    case Permission.camera:
      break;
    case Permission.contacts:
      break;
    case Permission.location:
    case Permission.locationAlways:
    case Permission.locationWhenInUse:
      tipsContext = getUItext()['PermissionLocationTips'];
      enImage = 'usingLocation';
      break;
    case Permission.mediaLibrary:
      break;
    case Permission.microphone:
      break;
    case Permission.phone:
      break;
    case Permission.photos:
      break;
    case Permission.photosAddOnly:
      break;
    case Permission.reminders:
      break;
    case Permission.sensors:
      break;
    case Permission.sms:
      break;
    case Permission.speech:
      break;
    case Permission.storage:
      break;
    case Permission.ignoreBatteryOptimizations:
      break;
    case Permission.notification:
      tipsContext = getUItext()['PermissionNotificationTips'];
      enImage = 'usingNotification';
      break;
    case Permission.accessMediaLocation:
      break;
    case Permission.activityRecognition:
      break;
    case Permission.unknown:
      break;

    case Permission.manageExternalStorage:
      break;
    case Permission.systemAlertWindow:
      break;
    case Permission.requestInstallPackages:
      break;
    case Permission.appTrackingTransparency:
      break;
    case Permission.criticalAlerts:
      break;
    case Permission.accessNotificationPolicy:
      break;
    case Permission.bluetooth:
    case Permission.bluetoothScan:
    case Permission.bluetoothAdvertise:
    case Permission.bluetoothConnect:
      tipsContext = getUItext()['PermissionBluetoothTips'];
      enImage = 'usingBle';
      break;
    case Permission.nearbyWifiDevices:
      break;
    case Permission.videos:
      break;
    case Permission.audio:
      break;
    case Permission.scheduleExactAlarm:
      break;
    case Permission.sensorsAlways:
      break;
    // case Permission.calendarReadOnly:
    //   break;
    case Permission.calendarFullAccess:
      break;
    default:
      break;
  }
  if (Platform.isIOS) {
    if (cb != null) {
      cb(true);
      cb = null;
    }
    return;
  }

  bool en = true;
  for (var element in permissions) {
    LOGI('--> $element ${await element.isGranted}');

    if (!await element.isGranted) {
      en = false;
      break;
    }
  }

  LOGI('$en');

  if (en == false) {
    dq_MsgBox(context, getUItext()['tips'], tipsContext, [
      getUItext()['cancel'],
      getUItext()['confirm'],
    ], (p0) async {
      if (p0 == getUItext()['confirm']) {
        for (var element in permissions) {
          res = await element.request();
          if (res.isDenied) {
            LOGI('申请被拒 $element');
            dq_showTips(context, getUItext()['userDeniedPermission']);
            if (cb != null) {
              cb!(false);
              cb = null;
            }
            return;
          }
        }
        if (cb != null) {
          cb!(true);
          cb = null;
        }
      } else {
        LOGI('取消申请 $permissions');
        dq_showTips(context, getUItext()['userDeniedPermission']);
        if (cb != null) {
          cb!(false);
          cb = null;
        }
      }
    }, enImage!);
  } else {
    if (cb != null) {
      cb(true);
      cb = null;
    }
  }
}
